<!--<template>-->
<!--  <div style="padding: 10px;">-->
<!--    <el-row :gutter="20">-->
<!--      &lt;!&ndash; 因子菜单 &ndash;&gt;-->
<!--      <el-col :span="10" :xs="24" class="left-board">-->
<!--        &lt;!&ndash; 因子搜索框 &ndash;&gt;-->
<!--        <div class="head-container">-->
<!--          <el-input-->
<!--            v-model="form.strategyNm"-->
<!--            placeholder="请输入策略名称"-->
<!--            style="margin-bottom: 10px"-->
<!--          />-->
<!--        </div>-->
<!--        &lt;!&ndash; 因子选择 &ndash;&gt;-->
<!--        <el-row>-->
<!--          &lt;!&ndash; 因子大类别 &ndash;&gt;-->
<!--          <el-col :span="4" class="components-factorCategory">-->
<!--            <div v-for="factorCategory in categoryList"-->
<!--                 :key="factorCategory.factorCategoryId"-->
<!--                 class="components-factorTitle"-->
<!--                 @click="getFactorList(factorCategory.factorCategoryId)">-->
<!--              {{ factorCategory.factorCategoryTitle }}-->
<!--            </div>-->
<!--          </el-col>-->
<!--          &lt;!&ndash; 因子 &ndash;&gt;-->
<!--          <el-col :span="20"-->
<!--                  style="height: 100vh;  padding-left: 8px; overflow: scroll">-->
<!--            <div v-for="factor in factorList" :key="factor.factorItemTitle"-->
<!--                 @click="addConditionItem(factor)"-->
<!--                 class="components-item">-->
<!--              <div class="components-body">-->
<!--                {{ factor.factorItemTitle }}-->
<!--              </div>-->
<!--            </div>-->
<!--          </el-col>-->

<!--        </el-row>-->
<!--        &lt;!&ndash;-->
<!--              </el-col>-->
<!--               生成策略表单-->
<!--      <el-col :span="14" :xs="24">-->
<!--        <el-scrollbar class="center-scrollbar">-->
<!--          <el-row class="center-board-row" :gutter="formConf.gutter">-->
<!--            <el-form-->
<!--              :size="formConf.size"-->
<!--              :label-position="formConf.labelPosition"-->
<!--              :disabled="formConf.disabled"-->
<!--              :label-width="formConf.labelWidth + 'px'"-->
<!--            >-->
<!--              <draggable class="drawing-board" :list="conditionItemList"-->
<!--                         :animation="340" group="componentsGroup">-->
<!--                <condition-item v-for="factorCategory in conditionItemList"-->
<!--                                :key="factorCategory.factorItemTitle"-->
<!--                                :factor-item-title="factorCategory.factorItemTitle">-->
<!--                </condition-item>-->
<!--              </draggable>-->
<!--              <div v-show="!conditionItemList.length" class="empty-info">-->
<!--                从左侧点选指标进行条件设置-->
<!--              </div>-->
<!--            </el-form>-->
<!--          </el-row>-->
<!--        </el-scrollbar>-->
<!--        <div style="align-content: center">-->
<!--          <el-button type="primary" @click="submitForm">提交1</el-button>-->
<!--          <el-button @click="resetForm">重置</el-button>-->
<!--        </div>-->
<!--        &ndash;&gt;-->
<!--      </el-col>-->
<!--      <el-col :span="300">-->
<!--        <el-row>-->
<!--          <el-col :span="10">请输入临时定义因子：</el-col>-->
<!--          <el-col :span="200">-->
<!--            <textarea v-model="form.strategyTmpFactor" type="textarea" placeholder="请输入临时因子例如：-->
<!--  T1=MAX:LY(1),LY(2)" style="width: 400px;height: 200px;color: #606266"/>-->
<!--          </el-col>-->
<!--        </el-row>-->
<!--        <el-row>-->
<!--          <el-col :span="10">请输入伪代码：</el-col>-->
<!--          <el-col :span="200">-->
<!--            <textarea v-model="form.strategyContent" type="textarea" placeholder="请输入伪代码例如：-->
<!--  C1:0.15<ROE3(1)<0.50;-->
<!--  C2:0<P5P10(1~5);-->
<!--  C3:TR20(1)=1;-->
<!--  C4:TR20(2)=0-->
<!--注意：按照现有规则输入，否则会通不过语法规则-->
<!--注：C1:0.15<ROE3(1)<0.50-->
<!--ROE3(1)代表ROE3当前值" style="width: 400px;height: 300px;color: #606266"/>-->
<!--          </el-col>-->
<!--        </el-row>-->

<!--      </el-col>-->


<!--      <textarea v-model="form.strategyContent" type="textarea" placeholder="请输入伪代码例如：-->
<!--      C1:0.15<ROE3(1)<0.50;-->
<!--      C2:0<P5P10(1~5);-->
<!--      C3:TR20(1)=1;-->
<!--      C4:TR20(2)=0-->
<!--      注意：按照现有规则输入，否则会通不过语法规则-->
<!--      注：C1:0.15<ROE3(1)<0.50-->
<!--      ROE3(1)代表ROE3当前值" style="width: 590px;height: 500px;color: #606266"/>-->

<!--      <div class="right-board">-->
<!--      <textarea v-model="form.longText" type="textarea" placeholder="请输入内容" style="width: 590px;height: 500px;"/>-->
<!--      </div>-->

<!--      <div style="align-content: center">-->
<!--        <el-input v-model="form.strategyLogic" type="textarea" maxlength="30"-->
<!--                  placeholder="表达式:C1xC2x((C3xC5)+(C4xC6))xC7"-->
<!--                  style="width: 40%;"-->
<!--                  onkeyup="this.value = this.value.toUpperCase()"/>-->
<!--        &lt;!&ndash;        <ol class="custom" contenteditable="true">&ndash;&gt;-->
<!--        &lt;!&ndash;          <li>First</li>&ndash;&gt;-->
<!--        &lt;!&ndash;          <li>Second</li>&ndash;&gt;-->
<!--        &lt;!&ndash;          <li>Third</li>&ndash;&gt;-->
<!--        &lt;!&ndash;          <li>Fourth</li>&ndash;&gt;-->
<!--        &lt;!&ndash;          <li>Fifth</li>&ndash;&gt;-->
<!--        &lt;!&ndash;          <li>Sixth</li>&ndash;&gt;-->
<!--        &lt;!&ndash;          <li>Seventh</li>&ndash;&gt;-->
<!--        &lt;!&ndash;          <li>Eighth</li>&ndash;&gt;-->
<!--        &lt;!&ndash;          <li>Ninth</li>&ndash;&gt;-->
<!--        &lt;!&ndash;          <li>Tenth</li>&ndash;&gt;-->
<!--        &lt;!&ndash;        </ol>&ndash;&gt;-->
<!--        <el-button type="primary" @click="submitForm1">提交</el-button>-->
<!--        <el-button @click="resetFormBD">重置</el-button>-->
<!--      </div>-->
<!--    </el-row>-->

<!--  </div>-->
<!--</template>-->

<template>
  <div class="app-container">
    <!--    因子选择区-->
    <div class="left-board">
      <!--因子类别-->
      <div>
        <el-row class="left-factor-header-list">
          <!-- 因子大类别 -->
          <el-col :span="4" class="components-factorCategory">
            <div v-for="factorCategory in categoryList"
                 :key="factorCategory.factorCategoryId"
                 class="components-factorTitle"
                 @click="getFactorList(factorCategory.factorCategoryId)">
              {{ factorCategory.factorCategoryTitle }}
            </div>
          </el-col>
          <!-- 因子 -->
          <el-col :span="20"
                  style="height: calc(100vh - 90px); overflow: scroll">
            <div v-for="factor in factorList" :key="factor.factorItemTitle"
                 @click="clickFactor(factor)"
                 class="components-item">
              <!--v-if="factor.factorItemTitle!=null"-->
              <el-popover

                placement="top-start"
                width="200"
                trigger="hover"
                :content="factor.factorItemTitle">
                <div class="components-body" slot="reference">
                  {{ factor.factorItemTitle }}
                </div>
              </el-popover>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <!--  条件编辑区-->
    <div class="center-board">
      <!--<el-input v-model="form.strategyCd" v-show="false"/>-->
      <el-row :gutter="40">
        <el-col :span="15">
          <el-form :model="form" :ref="form"
            :size="formConf.size"
            :label-position="formConf.labelPosition"
            :disabled="formConf.disabled"
            :label-width="formConf.labelWidth + 'px'">
            <el-form
                     label-width="120px" class="condition-edit">
              <el-form-item
                prop="email"
                label="因子构造"
                >
                <el-input v-model="form.strategyTmpFactor"
                          id="inputFactor"
                          @focus="checkFocus('inputFactor')"
                          placeholder="请输入临时因子例如： T1=MAX:LY(1),LY(2)"
                          type="textarea"
                          :autosize="{ minRows: 7, maxRows: 8}"></el-input>
              </el-form-item>
              <el-form-item
                prop="email"
                :rules="{required: true, message: '伪代码不能为空', trigger: 'blur'}"
                label="策略伪代码">
                <el-input id="inputCondition"
                          @focus="checkFocus('inputCondition')"
                          v-model="form.strategyContent"
                          placeholder="请输入伪代码例如：
  C1:0.15<ROE3(1)<0.50;
  C2:0<P5P10(1~5);
  C3:TR20(1)=1;
  C4:TR20(2)=0
注意：按照现有规则输入，否则会通不过语法规则
注：C1:0.15<ROE3(1)<0.50
ROE3(1)代表ROE3当前值" type="textarea"
                          :autosize="{ minRows: 8, maxRows: 9}" @keyup.enter.native="KeyUpEsc"></el-input>
              </el-form-item>
              <el-form-item
                label="策略表达式"
                :rules="{required: true, message: '表达式不能为空', trigger: 'blur'}">
                <el-input v-model="form.strategyLogic" focus="focusInput()"
                          placeholder="表达式:C1xC2x((C3xC5)+(C4xC6))xC7"></el-input>
              </el-form-item>
              <el-form-item
                label="额外展示指标">
                <el-input v-model="form.additionalIndex"
                          id="inputAdditionalIndex"
                          @focus="checkFocus('inputAdditionalIndex')"
                          placeholder="5GROE_5Y(1),ROA_5Y(1),ROIC_5Y(1),TTT(1)"></el-input>
              </el-form-item>
              <el-divider style="margin: 50px"></el-divider>
              <el-form-item label="策略名称"
                            :rules="[{ required: true, message: '策略名称不能为空', trigger: 'blur' }]">
                <el-input v-model="form.strategyNm" placeholder="请输入策略名称"
                          style="margin-bottom: 10px"/>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-document-add"
                           @click="submitForm1">保存策略
                </el-button>
                <el-button @click="resetFormBD">全部清空
                </el-button>
              </el-form-item>
            </el-form>
          </el-form>
        </el-col>
        <el-col :span="9">
          <div class="grid-content bg-purple">
            <el-scrollbar class="operator-list">
              <div class="components-list">
                <draggable
                  class="components-draggable"
                  :list="TbFactorOpList"
                  :group="{ name: 'componentsGroup', pull: 'clone', put: false }"
                  draggable=".components-item"
                  :sort="false"
                >
                  <div
                    v-for="(element, index) in TbFactorOpList" :key="index"
                    class="components-item"
                    @click="clickOpSymbol(element)"
                  >
                    <div class="components-body">
                      <!--                <svg-icon :icon-class="element.tagIcon"/>-->
                      {{ element.symbolNm + ' : ' + element.symbolExpress   }}
                    </div>
                  </div>
                </draggable>
              </div>
            </el-scrollbar>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import {
  listCategory,
  listFactor,
  getCategory,
  delCategory,
  addCategory,
  updateCategory,
  verifySom,
  addCategorys
} from '@/api/system/category'
import draggable from 'vuedraggable'
import ConditionItem from './ConditionItem'
import { listTbFactorOp } from '@/api/system/TbFactorOp'

import { getStrategy,updateStrategy} from "@/api/system/strategy";


export default {
  components: {
    ConditionItem,
    draggable
  },
  name: 'Category',
  data() {
    return {
      activeName2: 'first',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 因子类别表格数据
      categoryList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      strategyNm: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        factorCategoryId: null,
        factorCategoryTitle: null,
        sort: null,
        isdelete: null,
        additionalIndex:null,
        // strategyCd:null,
        isdouble: null,
        strategyTmpFactor:null,
        symbolNm: null,
        symbolExpress: null,
        symbolTypeCd: null,
        isInvalid: null,
        createTm: null
      },
      // 表单参数
      form: {
        strategyCd:'',
        strategyTmpFactor: '',
        strategyNm:'',
        strategyLogic:'',
        additionalIndex:'',
        strategyContent: ''
      },
      // 表单校验
      rules: {},
      //因子类别 id
      factorCategoryId: '',
      //因子列表
      factorList: [],
      //因子名称，用作搜索用
      factorItemTitle: null,

      //
      formConf: {
        formRef: 'elForm',
        formModel: 'formData',
        size: 'medium',
        labelPosition: 'right',
        labelWidth: 100,
        formRules: 'rules',
        gutter: 15,
        disabled: false,
        span: 24,
        formBtns: true
      },
      conditionItemList: [],
      TbFactorOpList: [],
      strategyContentIndex: 0
    }
  },
  watch: {
    // 根据名称筛选因子
    factorItemTitle(val) {
      this.$refs.tree.filter(val)
    }
  },
  activated () {
    if(this.$route.query.strategyCd!=null){
      this.getgetStrategy()
    }else {
      this.reset()
    }
  },
  created() {
    this.getList()
    this.getFactorList()
    this.getOperatorList()
    if(this.$route.query.strategyCd!=null){
      this.getgetStrategy()
    }

  },
  methods: {
    activeFormItem(element) {
      this.activeData = element
      this.activeId = element.formId
    },
    KeyUpEsc: function() {

      var subStr = this.form.strategyContent.trim().substr(this.form.strategyContent.trim().length-1,1);
      if(subStr!=";")
        this.form.strategyContent=this.form.strategyContent.trim()+";"+"\n";
      // alert(1111);
      var ss=this.form.strategyContent.split(';');
      // alert(ss);
      if(ss[ss.length-2].indexOf(":") == -1){
        this.form.strategyContent=this.form.strategyContent.trim();
        return this.$modal.msgError("伪代码不合法：【没有冒号】");
      }
      if(ss[ss.length-2].indexOf("<") == -1&&ss[ss.length-2].indexOf(">") == -1&&ss[ss.length-2].indexOf("=") == -1){
        this.form.strategyContent=this.form.strategyContent.trim();
        return this.$modal.msgError("伪代码不合法：【没有比较运算符】");
      }

      // alert(ss[ss.length-2]);
      var bm=ss[ss.length-2].split(":")[0].replace(/\d+/g,'').trim();
      if(bm==""){
        this.form.strategyContent=this.form.strategyContent.trim();
        return this.$modal.msgError("别名不能为纯数字！");
      }
      var data=ss[ss.length-2]
      verifySom(data).then(response => {
        if (response.msg != '验证成功') {
          this.form.strategyContent=this.form.strategyContent.trim();
          return this.$modal.msgError(response.msg);
        }else {
          this.form.strategyContent=this.form.strategyContent+bm+ss.length+":";
        }
      });


      // alert(this.form.strategyContent);
    },
    /** 查询因子类别列表 */
    getList() {
      // this.reset();
      this.loading = true;
      listCategory(this.queryParams).then(response => {
        this.categoryList = response.rows
        this.total = response.total
        this.loading = false
        // this.conditionItemList = response.rows;
      })
    },

    getgetStrategy() {
      // this.reset();
      this.loading = true;
      var strategyCd=this.$route.query.strategyCd;
      // alert(strategyCd);
      getStrategy(strategyCd).then(response => {
        this.form = response.data;
        this.open = false;
        this.title = "修改策略生成";
      });
    },
    /** 提交按钮 */
    submitForm1() {
      // alert(this.form.strategyCd);
      // return

      if (this.form.strategyNm == null || this.form.strategyNm == '') {
        return this.$modal.msgError('策略名称不能为空！')
      }
      if (this.form.strategyContent == null || this.form.strategyContent == '') {
        return this.$modal.msgError('策略伪代码不能为空！')
      }

      if (this.form.strategyLogic == null || this.form.strategyLogic == '') {
        return this.$modal.msgError('策略表达式不能为空！')
      }

          if (this.form.strategyCd != null &&this.form.strategyCd != "") {
            updateStrategy(this.form).then(response => {
              if (response.msg == '修改成功') {
                this.$modal.msgSuccess(response.msg)
                this.$store.dispatch('tagsView/delView', this.$route)
// /             / 返回上一步路由
                this.$router.go(-1)
              } else {
                this.$modal.msgError(response.msg)
              }

            });
          } else {
            addCategorys(this.form).then(response => {
              console.log('添加策略', this.form, response)
              if (response.msg == '新增成功') {
                this.$modal.msgSuccess(response.msg)
                this.$router.push('/strategy/strategy');
                // this.$store.dispatch('/strategy/strategy', this.$route);
//                 this.$store.dispatch('tagsView/delView', this.$route)
// // /             / 返回上一步路由
//                 this.$router.go(-1)
              } else {
                this.$modal.msgError(response.msg)
              }
            })
          }





      // alert(1111);

    },

    // 查询因子列表
    getFactorList(factorCategoryId) {
      if (factorCategoryId == null) {
        factorCategoryId = '100'
      }
      this.loading = true
      this.queryParams.factorCategoryId = factorCategoryId
      listFactor(this.queryParams).then(response => {
        this.factorList = response.rows
        this.loading = false
      })
    },
    //查询运算符列表
    getOperatorList() {
      this.loading = true
      listTbFactorOp(this.queryParams).then(response => {
        this.TbFactorOpList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    //
    checkFocus(e) {
      this.focusId = e
    },
    //点击因子
    clickFactor(item) {
      const elem = document.getElementById(this.focusId)
      const symbol = item.factorItemTitle
      var result = symbol.match(/\(([^)]*)\)/);
      this.insertSomething(elem, result[1]+"(1)")
    },
    //点击运算符
    clickOpSymbol(item) {
      const elem = document.getElementById(this.focusId)
      this.insertSomething(elem, item.symbolExpress)
    },
    //光标后插入内容
    insertSomething(elem, insertStr) {
      const start = elem.selectionStart
      const end = elem.selectionEnd
      const selection = elem.selection
      if (this.focusId === 'inputFactor') {
        let str = this.form.strategyTmpFactor
        if (str == null || str === '') {
          this.form.strategyTmpFactor = insertStr
        } else {
          this.form.strategyTmpFactor = str.slice(0, start) + insertStr + str.slice(end)
        }
      } else if (this.focusId === 'inputCondition') {
        let str = this.form.strategyContent
        if (str == null || str === '') {
          this.form.strategyContent =  insertStr
        } else {
          this.form.strategyContent = str.slice(0, start) + insertStr + str.slice(end)
        }
      }else if (this.focusId === 'inputAdditionalIndex') {
        let str = this.form.additionalIndex
        if (str == null || str === '') {
          this.form.additionalIndex =  insertStr
        } else {
          this.form.additionalIndex = str.slice(0, start) + insertStr + str.slice(end)
        }
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    resetFormBD() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      // alert(1111);
      this.form = {
        factorCategoryId: null,
        factorCategoryTitle: null,
        sort: null,
        isdelete: null,
        strategyNm: null,
        additionalIndex:null,
        isdouble: null,
        strategyCd:null,
        strategyLogic: null,
        strategyTmpFactor: null,
        strategyContent: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.factorCategoryId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    //重置
    resetForm() {
      this.$refs['elForm'].resetFields()
    },
    // resetForm(form) {
    //   alert(1111)
    //   this.$refs[form].resetFields()
    // },
    handleClick(tab, event) {
      // console.log(tab, event);
    }
  }
}
</script>

<style lang='scss'  scoped>

$selectedColor:#f6f7ff;


.app-container {
  height: calc(100vh - 80px);
  width: 100%;
  padding: 10px;
  display: flex;
}

.left-board {
  width: 360px;
  height: calc(100vh - 80px);
}

.left-factor-header-list {
  display: flex;
  height: calc(100vh - 80px);

  .components-factorCategory {
    background: #F0F1FF;
    height: calc(100vh - 80px);;
    box-shadow: 1.5px 0 1px #E6E8FF;
  }

  //
  .components-factorTitle {
    font-size: 13px;
    font-weight: bold;
    color: #222;
    text-align: center;
    margin-top: 10px;
    flex: 1;

    &:hover {
      color: #787be8;
      background: #E6E8FF;
    }
  }

  .components-item {
    display: inline-block;
    width: 48%;
    margin: 1%;
    transition: transform 0ms !important;
  }
}


.components-body {
  padding: 8px 10px;
  background: $selectedColor;
  font-size: 12px;

  .svg-icon {
    color: #777;
    font-size: 15px;
  }

  &:hover {
    color: #787be8;
    background: #E6E8FF;
    border-radius: 3px;
  }
}

.center-board {
  height: 100%;
  padding: 0 10px;
  flex: 1;
  display: flex;
  //padding: 10px;

  .components-list {
    padding: 8px;
    box-sizing: border-box;
    height: 100%;

    .components-item {
      display: inline-block;
      width: 48%;
      margin: 1%;
      transition: transform 0ms !important;
    }
  }

  .components-body {
    padding: 8px 10px;
    background: $selectedColor;
    font-size: 12px;
    cursor: default;
    border: 1px dashed $selectedColor;
    border-radius: 3px;
  }

  .el-row {
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .operator-list {
    height: calc(100vh - 80px);
    //overflow: hidden;
  }

}


</style>
